package com.example.mywanandroid.home;

import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager.widget.PagerAdapter;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

public class ViewPagerAdatper extends PagerAdapter {
    List<ViewPagerItem> viewList;
    List<ImageView> imageViewList;
    FragmentActivity currentActivity;

    public ViewPagerAdatper(List<ViewPagerItem> viewList, FragmentActivity currentActivity) {
        this.viewList = viewList;
        this.currentActivity = currentActivity;
        imageViewList = new ArrayList<>();
        initImageViewList(viewList);
    }
    @Override
    public int getCount() {
        return viewList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        container.removeView(imageViewList.get(position));
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        container.addView(imageViewList.get(position));
        return imageViewList.get(position);
    }

    public void initImageViewList(List<ViewPagerItem> viewPagerList) {
        for (final ViewPagerItem item : viewPagerList) {
            final ImageView img = new ImageView(currentActivity);
            Glide.with(currentActivity).load(item.getImagePath()).into(img);
            // 点击ViewPager图片弹出新页面
            img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String link = item.getUrl();
                    Intent intent = new Intent(currentActivity, WebViewActivity.class);
                    intent.putExtra("link", link);
                    currentActivity.startActivity(intent);
                }
            });
            imageViewList.add(img);
        }
    }

    public void refresh(List<ViewPagerItem> viewPagerList) {
        imageViewList.removeAll(imageViewList);
        initImageViewList(viewPagerList);
        notifyDataSetChanged();
    }
}
